package com.training1.core.common.utils.framework;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import com.training1.core.common.global.Global;
import com.training1.core.common.global.SpringContextHolder;

public class MailUtil {

	private static final Logger log = LoggerFactory.getLogger(MailUtil.class);
	
	public static void sendMail(String title,String content){
		String destination = getDestination();
		sendMail(destination, title, content);
	}
	
	
	public static void sendMail(String destination,String title,String content){
		JavaMailSenderImpl javaMail = getJavaMail();
		SimpleMailMessage mail = new SimpleMailMessage();
		mail.setTo(destination);
		mail.setFrom(javaMail.getUsername());
		mail.setText(content);
		mail.setSubject(title);
		try {
			javaMail.send(mail);
			log.info("发送邮件成功:目的地:{},主题:{},内容:{}",destination,title,content);
		} catch (Exception e) {
			log.warn("发送邮件失败:目的地:{},主题:{},内容:{}",destination,title,content);
			log.warn("发送邮件失败",e);
		}
	}
	
	private static JavaMailSenderImpl getJavaMail(){
		return SpringContextHolder.getBean(JavaMailSenderImpl.class);
	}
	
	private static String getDestination(){
		return Global.getConfig("mail.to");
	}
}
